package hqu.cst.XAH.service.imp;

import hqu.cst.XAH.mapper.MovieMapper;
import hqu.cst.XAH.pojo.Movie;
import hqu.cst.XAH.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;

@Service
public class MovieServiceImp implements MovieService {

    private static final String POSTER_DIRECTORY = "E:\\Desktop\\lecture\\src\\main\\resources\\static";
    @Autowired
    private MovieMapper movieMapper;

    @Override
    public List<Movie> getAllMovies() {
        return movieMapper.getAllMovies();
    }

    @Override
    public ResponseEntity<Movie> getMovieById(Long id) {
        Movie movie = movieMapper.getMovieById(id);
        if (movie == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(movie);
    }

    @Override
    public void addMovie(Movie movie) {
        movieMapper.insertMovie(movie);
    }

    @Override
    public void deleteMovie(Long id) {
        movieMapper.deleteMovieById(id);
    }

    @Override
    public void uploadPoster(Long id, MultipartFile file) throws IOException {
        // 获取电影记录
        Movie movie = movieMapper.getMovieById(id);
        if (movie == null) {
            throw new FileNotFoundException("Movie not found");
        }

        // 保存文件
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        Path filePath = Paths.get(POSTER_DIRECTORY, fileName);
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

        // 更新数据库中的 posterUrl
        movie.setPosterUrl(fileName);
        movieMapper.updateMovie(movie);
    }

    @Override
    public Resource downloadPoster(Long id) throws IOException {
        // 获取电影记录
        Movie movie = movieMapper.getMovieById(id);
        if (movie == null || movie.getPosterUrl() == null) {
            throw new FileNotFoundException("Poster not found for movie ID: " + id);
        }

        // 加载文件资源
        Path filePath = Paths.get(POSTER_DIRECTORY, movie.getPosterUrl());
        Resource resource = new UrlResource(filePath.toUri());

        if (resource.exists() && resource.isReadable()) {
            return resource;
        } else {
            throw new FileNotFoundException("Poster file not found: " + movie.getPosterUrl());
        }
    }
}
